package controlcenter

import (
	"errors"
	"gitee.com/hakwolf/dbmagic/golib/internal/models"

	"gitee.com/hakwolf/dbmagic/golib/internal/modules/logger"
)

const (
	ControlNone = iota
	ControlShare
	ControlFtp
	ControlQiNiu
	ControlBaiduDisk
)

type ControlCenterForm struct {
	Id   int `json:"id" xorm:"smallint pk autoincr"`
	Xid  int `json:"xid" xorm:"int"`
	Type int `json:"type" xorm:"int"`
	Tid  int `json:"tid" xorm:"int"`
}

// All 获取所有主机
func UIAll(taskid int) []models.ControlCenter {
	ccenterModel := new(models.ControlCenter)
	ccenterModel.PageSize = -1
	commonMap := models.CommonMap{}
	commonMap["Xid"] = taskid
	centers, err := ccenterModel.List(commonMap)
	if err != nil {
		logger.Error(err)
		return nil
	}
	return centers
}

// Store 保存、修改主机信息
func UIStore(form ControlCenterForm) (error, int) {
	ControlCenterModel := new(models.ControlCenter)
	id := form.Id
	var err error
	nameExist, err := ControlCenterModel.CenterTargetExists(form.Xid, form.Type, form.Tid)
	if err != nil {
		err = errors.New("操作失败")
		return err, id //return json.CommonFailure("操作失败", err)
	}
	if nameExist {
		err = errors.New("当前备份目标已存在，添加失败")
		return err, id //		return err, "主机别名已存在", id //return json.CommonFailure("主机别名已存在")
	}
	ControlCenterModel.Xid = form.Xid
	ControlCenterModel.Type = form.Type
	ControlCenterModel.Tid = form.Tid

	if id > 0 {
		_, err = ControlCenterModel.UpdateBean(id)
	} else {
		id, err = ControlCenterModel.Create()
	}
	if err != nil {
		err = errors.New("保存失败！")
		return err, id //return err, "保存失败", id //return json.CommonFailure("保存失败", err)
	}

	return nil, id //return nil, "保存成功", id
}

// Remove 删除主机
func UIRemove(id int) error {
	//id, err := strconv.Atoi(ctx.Params(":id"))
	//json := utils.JsonResponse{}
	//if err != nil {
	//	return json.CommonFailure("参数错误", err)
	//}
	//taskHostModel := new(models.TaskHost)
	//exist, err := taskHostModel.HostIdExist(int16(id))
	//if err != nil {
	//	return json.CommonFailure("操作失败", err)
	//}
	//if exist {
	//	return json.CommonFailure("有任务引用此主机，不能删除")
	//}
	//
	var err error
	if id <= 0 {
		err = errors.New("参数错误")
		return err
	}
	ControlCenterModel := new(models.ControlCenter)
	err = ControlCenterModel.Find(int(id))
	if err != nil {
		err = errors.New("实例不存在")
		return err //return json.CommonFailure("主机不存在")
	}

	_, err = ControlCenterModel.Delete(id)
	if err != nil {
		err = errors.New("操作失败") //return json.CommonFailure("操作失败", err)
		return err
	}
	return nil
	//
	//addr := fmt.Sprintf("%s:%d", hostModel.Name, hostModel.Port)
	//grpcpool.Pool.Release(addr)
	//
	//return json.Success("操作成功", nil)

}
